﻿using commonImportPlugin.Common;
using commonImportPlugin.Configs.MatchFile;
using commonImportPlugin.Factorys;
using ICMS.PluginInterfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace commonImportPlugin.Core.FilesCore.MatchFile
{
    /// <summary>
    /// 《普通模式通用解析匹配文件数据核心类》
    /// 该模式支持匹配文件内容以行为单位，行内
    /// 数据项以特定分隔符分割。该模式支持绝大
    /// 部分匹配数据
    /// </summary>
    public class MatchFileCoreClass : MatchFileCore
    {
        static MatchFileConfig config = null;
        MatchFileBase matchFileBase = new MatchFileBase();
        static Context context;
        public MatchFileCoreClass GetInstance()
        {
            if(IsGetConfigSucceed())
            {
                context = Context.GetConfig();
                return new MatchFileCoreClass();
            }           
            return null;   
        }
        private bool IsGetConfigSucceed()
        {
            config=MatchFileConfig.GetConfig();     
            if (config == null)
                return false;
            else
                return true;
        }
        /// <summary>
        /// 获取所有的匹配数据
        /// </summary>
        /// <param name="matchFilePaths">匹配文件集</param>
        /// <param name="matchCounts">成功获取到的数据量</param>
        /// <returns>获取到的匹配数据</returns>
        public override List<ICData> GetMatchAllDatas(List<string> matchFilePaths, out int matchCounts)
        {
            List<ICData> allMatchDatas = new List<ICData>();

            foreach (string medicalFile in matchFilePaths)
            {
                matchFileBase.GetFileMatchDatas(allMatchDatas, medicalFile, config);
            }

            matchCounts = allMatchDatas.Count;
            return allMatchDatas;  
        }

        public override bool CheckMatchData(string matchFilePath, string regexstr)
        {
            throw new NotImplementedException();
        }
        /// <summary>
        /// 获取匹配的总数据量
        /// </summary>
        /// <param name="matchFilePaths">成功获取到的数据量</param>
        /// <returns>匹配数据总量</returns>
        public override int GetMatchAllCounts(List<string> matchFilePaths)
        {
            int allMatchCount = 0;

            foreach (string matchlFile in matchFilePaths)
            {
                string[] originTrackLines = null;

                if (!File.Exists(matchlFile))
                    throw new Exception("匹配文件不存在！");

                originTrackLines = File.ReadAllLines(matchlFile, ASCIIEncoding.GetEncoding(config.encoding));

                int eachFileCount = originTrackLines.Length - config.dataIndex + 1;
                allMatchCount += eachFileCount;
            }

            return allMatchCount;
        }
    }
}
